package com.tomagency.cyberlab.server.util;


import java.io.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;


public class ServletHelper {
	
	/**
	 * Hilfsklasse für servlets
	 */

	
	public static final String XML_UTF8_HEADER="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
	public static final String CHARSET_UFT8="UTF-8";
	public static final String CHARSET_ISO="ISO-8859-1";
	
	  
	  public static boolean saveXmlUTF8Body(String filePath,String xml){

		  File file = new File(filePath);
		  boolean ok=true;
		  BufferedWriter out=null;
		try {
				out = new BufferedWriter(new OutputStreamWriter
				          (new FileOutputStream(file),CHARSET_UFT8));
			
	
				out.write(XML_UTF8_HEADER);
				out.write(xml);				
				out.close();
			} 
			catch (Exception e) {
				ok=false;
				Logger.getLogger(ServletHelper.class).error("Fehler beim Schreiben des Files: "+filePath, e);
			}
			finally{
				if (out!=null){
					try 
					{
						out.close();
					} 
					catch (IOException e) {
					}
				}
			}
		return ok;
		  
	  }
	  
	  public static boolean saveXmlUTF8Body(File file,String xml){

		  boolean ok=true;
		  BufferedWriter out=null;
		try {
				out = new BufferedWriter(new OutputStreamWriter
				          (new FileOutputStream(file),CHARSET_UFT8));
			
	
				out.write(XML_UTF8_HEADER);
				out.write(xml);				
				out.close();
			} 
			catch (Exception e) {
				ok=false;
				Logger.getLogger(ServletHelper.class).error("Fehler beim Schreiben des Files: "+file.getAbsolutePath(), e);
			}
			finally{
				if (out!=null){
					try 
					{
						out.close();
					} 
					catch (IOException e) {
					}
				}
			}
		return ok;
		  
	  }
	 	  
	  public static String readXmlUFT8File(String filePath){
		  
		  File file = new File(filePath);
		  if (!file.canRead()){
			  Logger.getLogger(ServletHelper.class).error("Fehler beim Lesen des Files"+filePath);
			  return null;
		  }
		  
		  String xml=null;
		try {
			xml = getFileContent(file,CHARSET_UFT8).toString();
		} 
		catch (Exception e) {
			Logger.getLogger(ServletHelper.class).error("Fehler beim Lesen des Files: "+filePath, e);
			
		}		  
		  return xml;		  
		  
	  }
	  
	  public static boolean saveTextFile(String filePath,String text,String charSet){

		  File file = new File(filePath);
		  boolean ok=true;
		  BufferedWriter out=null;
		try {
				out = new BufferedWriter(new OutputStreamWriter
				          (new FileOutputStream(file),charSet));
			
	
				out.write(text);				
				out.close();
			} 
			catch (Exception e) {
				ok=false;
				Logger.getLogger(ServletHelper.class).error("Fehler beim Schreiben des Files: "+filePath, e);
			}
			finally{
				if (out!=null){
					try 
					{
						out.close();
					} 
					catch (IOException e) {
					}
				}
			}
		return ok;
		  
	  }
	  
	  public static boolean saveTextFile(File file,String text,String charSet){

		  boolean ok=true;
		  BufferedWriter out=null;
		try {
				out = new BufferedWriter(new OutputStreamWriter
				          (new FileOutputStream(file),charSet));
			
	
				out.write(text);				
				out.close();
			} 
			catch (Exception e) {
				ok=false;
				Logger.getLogger(ServletHelper.class).error("Fehler beim Schreiben des Files: "+file.getAbsolutePath(), e);
			}
			finally{
				if (out!=null){
					try 
					{
						out.close();
					} 
					catch (IOException e) {
					}
				}
			}
		return ok;
		  
	  }
	  
	  public static StringBuilder getFileContent(File file,String charSet)
      throws FileNotFoundException, IOException 
	 {
	     InputStream in = null;
	     StringBuilder content = new StringBuilder();
	     try 
	     {
	       in = new BufferedInputStream(new FileInputStream(file));
	       byte[  ] buf = new byte[4 * 1024];  // 4K buffer
	       int bytesRead;
	       
	       while ((bytesRead = in.read(buf)) != -1) 
	       {
	         //out.write(buf, 0, bytesRead);
	         content.append(new String(buf, 0, bytesRead,charSet));
	       }
	     }
	     finally 
	     {
	       if (in != null) in.close(  );
	       
	     } 
	     
	     return content;
	}
	  
	  
	  public static void sendFile(File file, OutputStream out)
	      throws FileNotFoundException, IOException 
	 {
	     InputStream in = null;
	     try 
	     {
	       in = new BufferedInputStream(new FileInputStream(file));
	       byte[  ] buf = new byte[4 * 1024];  // 4K buffer
	       int bytesRead;
	       while ((bytesRead = in.read(buf)) != -1) 
	       {
	         out.write(buf, 0, bytesRead);
	       }
	     }
	     finally 
	     {
	       if (in != null) in.close(  );
	       out.flush();
	     } 
	}
	  

		  

	  public static int getCodedStringLength(String text,String charSet){
		  String s=null;
		  try {
			  return text.getBytes(charSet).length;
		  } catch (UnsupportedEncodingException e) {
			  // TODO Auto-generated catch block
			  e.printStackTrace();
		  }

		  return 0;

	  }
	  
	 public static void setRespNoChache(HttpServletResponse res)
	 {
	     // Set to expire far in the past.
	       res.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
	
	       // Set standard HTTP/1.1 no-cache headers.
	       res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
	
	       // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
	       res.addHeader("Cache-Control", "post-check=0, pre-check=0");
	
	       // Set standard HTTP/1.0 no-cache header.
	       res.setHeader("Pragma", "no-cache");
	
	 }
	 
	 static long getIpAdrValue(java.net.InetAddress ipAdr)
	 {
	     long ipAdrValue=0;
	
	     byte[] adrArray = ipAdr.getAddress();
	     long multiplikator = 1;
	     for (int i = adrArray.length-1;i>=0;i--)
	     {
	         ipAdrValue = ipAdrValue+adrArray[i]*multiplikator;
	         multiplikator *=256;
	     }
	
	     return ipAdrValue;
	 }
	 
		public static void sendResponse(HttpServletResponse resp, String responseString ,String contentType,String charCodierung)
		throws ServletException, IOException {
			
			resp.setContentType(String.format("%s;charset=%s",contentType,charCodierung));
			
			int codiertelaenge=ServletHelper.getCodedStringLength(responseString, charCodierung);
			//loggingUtil.getLogger(this.getClass()).log(Level.INFO, 
			//"response laenge: "+responseString.length() +"  "+ reqConfig.getResponseCharCodierung()+"-laenge: "+codiertelaenge
			//);
			
			//String encodedString = HelperUtil.newUTF8String(responseText.toString());
			resp.addHeader("Content-Length", Integer.toString(codiertelaenge));
			
			//Antwort schreiben
			ServletOutputStream out = resp.getOutputStream();
			java.io.OutputStreamWriter osWriter = new java.io.OutputStreamWriter(out,charCodierung);
			osWriter.write(responseString);
			osWriter.flush();
			osWriter.close();

		}

		



}
